

import UNetIdentity, { StepData } from "../UNet/UNetIdentity";
import { UNetMgr } from "../UNet/UNetMgr";
import CharacterControllers from "./CharacterControllers";
import Game from "./Game";

const {ccclass, property} = cc._decorator;

@ccclass
export default class Player extends UNetIdentity {
    @property(cc.Label)
    nickName : cc.Label = null;

    swordid : number = 0;

    control : CharacterControllers = null;

    sid:number = 0;

    onLoad(){
        super.onLoad()
        this.node.on('input_attack',this.onInputAttck,this)
        this.node.on('input_change',this.onChangeSword,this)
    }

    onInputAttck(k:number){
        this.SendCMD({c:'blt',id:this._uuid+(this.sid++),t:k,x:this.node.x,y:this.node.y+50});
    }
    onChangeSword(){
        // this.setSword(1-this.swordid);
        this.SendCMD({c:'swd',v:1-this.swordid})
    }

    setSword(wd:number){
        this.swordid = wd
        wd?this.node.getChildByName('icon').color = cc.Color.RED : this.node.getChildByName('icon').color = cc.Color.WHITE
    }
    /** 主角初始化 本方法在OnSyncUserInfo后执行 */
    OnSelfPlayerInit(){
        this.control = this.node.addComponent(CharacterControllers)
    }

    // /** 人物头像、名字等属性初始化 */
    OnSyncUserEnter(data){
        this.userData = data;
        this.nickName.string = data.nickname
    }

    /** 帧同步主要函数 */
    OnFrameUpdate(data:StepData){
        if(data.cmds && data.cmds.length > 0){
            for(var i=0; i<data.cmds.length; i++){
                var cmd = data.cmds[i]
                if(cmd.c == 'blt'){
                    Game.Instance.addBullet(cmd.id,cmd.t,cmd.x,cmd.y)
                } else if(cmd.c == 'swd'){
                    this.setSword(cmd.v);
                }
            }
        }
        super.OnFrameUpdate(data);
    }

    // /** 首次或重连时同步场景数据 */
    OnSyncSceneData(data:any){
        super.OnSyncSceneData(data)
        data.d && this.setSword(data.d.sword)
        this.node.opacity = 255;
        this.node.getChildByName('name').stopAllActions();
        this.node.getChildByName('name').opacity = 255;
    }

    OnGetSyncUserData(){
        return {sword:this.swordid}
    }

    OnSyncUserExit(data){
        super.OnSyncUserExit(data)
        if(UNetMgr.canOffline){
            this.node.opacity = 120;
            this.node.getChildByName('name').runAction(cc.repeatForever(cc.blink(2,2)))
        }
        return false
    }

    // onChangeControl(){
    //     console.log('lastDirection:',this.control.lastDirection)
    //     this.syncCMD.dir = {x:this.control.lastDirection.x,y:this.control.lastDirection.y,z:0}
    // }
}
